﻿using System.Net.Http;
using System.Net.Http.Formatting;
using Sustainalytics.LongRunningTaskManager;
using Sustainalytics.LongRunningTaskManager.Interface;
using Sustainalytics.OAuth.Services.Common.Client;
using System.Collections.Generic;


namespace Sustainalytics.ScreeningTool.Tasks
{
   internal  class CUSIPISINError
    {
        public int ErrorStatusCode { get; set; }
        public string Message { get; set; }
    }
    public class ExportExcelTask : ILongRunningTask
    {
        public LongRunningTaskTypeEnum Type
        {
            get { return LongRunningTaskTypeEnum.ScreeningToolExcel; }
        }

        public object Start(LongRunningTaskContext context)
        {
            var file = new LongRunningTaskFileInMemResult
            {
                FileName = context.Title + ".xlsx",
                MimeType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
                
                // get contents async from screening tool service
                Contents = CreateOWINController(context)
            };
            
            return file;
        }

        private byte[] CreateOWINController(LongRunningTaskContext context)
        {
            OAuthClient oAuthClient = new OAuthClient(
                HostConfig.GetHostUrl() + HostConfig.GetReportResource() + "/token",
                HostConfig.GetHostUrl() + HostConfig.GetReportResource(),
                null,
                null);

            oAuthClient.SetAuthenticationTicket(context.Ticket);

            HttpResponseMessage resp = oAuthClient.PostAsync(HostConfig.GetHostUrl() + HostConfig.GetReportResource(), new ObjectContent<string>(context.ParamJson, new JsonMediaTypeFormatter()), context.CancellationToken).Result;

            byte[] result = new byte[0];           

            if (!resp.IsSuccessStatusCode && resp.StatusCode == System.Net.HttpStatusCode.Forbidden )
            {
                var error = resp.Content.ReadAsAsync<CUSIPISINError>( new[] { new JsonMediaTypeFormatter() }).Result;
                if (error == null)
                    error = new CUSIPISINError { ErrorStatusCode = 1010, Message = "Unable to identify more details" };

                context.Title = error.Message;
                context.TaskStatus.AddError(new LongRunningTaskError
                {
                    ErrorCode = (int)error.ErrorStatusCode,
                    Arguments = new List<string> { error.Message}
                });
            }
            else
            {
                resp.EnsureSuccessStatusCode();                
                result = resp.Content.ReadAsByteArrayAsync().Result;
            }
            context.TaskStatus.Progress = 100;

            return result;
        }


       
    }
}
